﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class BestPosNum
{
    public int selfNum;
    public int elseNum;
    public int Calnum;
    public int pos;
}


public class EnemyAI : MonoBehaviour {

    public static EnemyAI _instance;

    public int RoundIndex = 0;
    private int MainAttack = 0;
    private List<Food> HelpFooder = new List<Food>();
    private byte HelpAttacker = 0;
    private bool isDamagePlayer = false;
    public int Combo;
    public int ComboHealth;

    void Awake()
    {
        _instance = this;
    }

    
    //public void EnemyAttack()
    //{
    //    List<Food> foods = new List<Food>();
    //    foods = TeamManager._instance.EnemyFoods;
    //    for (int i = 0; i < foods.Count; i++)
    //    {
    //        RandomPos(foods[i]);
    //        foreach (Food playerfood in TeamManager._instance.PlayerFoods)
    //        {
    //            foreach (int a in foods[i].AttackRangeMapGridID)
    //            {
    //                int mapgridid = MapManager._instance.CalcuMapGridID(playerfood.foodPosX, playerfood.foodPosY);

    //                if (a == mapgridid)
    //                {
    //                    playerfood.OnDamage(foods[i].foodInfo.AttackForce);
    //                    Debug.Log("在第" + RoundIndex + "回合" + "敌人   " + foods[i].foodInfo.FoodName + "   对你的   " + playerfood.foodInfo.FoodName + "   造成了" + foods[i].foodInfo.AttackForce + "点伤害");
    //                }
    //            }
    //        }
    //    }

    //    RoundIndex++;

    //    TurnGame._instance.mState = OperatorState.PlayerRound;
    //    TurnGame._instance.GameControl();
    //}

    public void RandomPos()
    {
        int Pos = LookingForTheBestPos();
        GameObject mapgrid = MapManager._instance.GetMapGridGo(Pos);

        int mapPosX = (int)(Pos / MapManager._instance.MapY);
        int mapPosY = Pos % MapManager._instance.MapY; ;

        if (mapgrid.transform.childCount == 0)
        {
            TeamManager._instance.EnemyFoods[MainAttack].SetGoPos(mapPosX, mapPosY);
        }
    }


    private ArrayList CalATKRangeById(int id, Food food)
    {
        ArrayList ATKRange = new ArrayList();

        int x = (int)(id / MapManager._instance.MapY);
        int y = id % MapManager._instance.MapY;

        int attackRangePosX = 0;
        int attackRangePosY = 0;
        //Debug.Log(foodInfo.AttackRange.Length);
        for (int i = 0; i < food.foodInfo.AttackRange.Length; i += 2)
        {
            attackRangePosX = food.foodInfo.AttackRange[i] + x;
            attackRangePosY = food.foodInfo.AttackRange[i + 1] + y;
            //Debug.Log(MapManager._instance.MapX + "   " + attackRangePosY);
            if (attackRangePosX >= 0 && attackRangePosX < MapManager._instance.MapX && attackRangePosY >= 0 && attackRangePosY < MapManager._instance.MapY)
            {
                int MapGridID = MapManager._instance.CalcuMapGridID(attackRangePosX, attackRangePosY);
                ATKRange.Add(MapGridID);
                //Debug.Log(i + "  " + MapGridID + "  " + AttackRangeMapGridID[a] + "  " + a);
            }
        }
        return ATKRange;
    }

    private int LookingForTheBestPos()
    {
        List<BestPosNum> bestPosList = new List<BestPosNum>();
        //先找到最多的位置，把敌人和自己的数量存下来
        for (int i = 0; i < 107; i++)
        {
            BestPosNum bestPosNum = new BestPosNum();

            foreach (int mapid in CalATKRangeById(i, TeamManager._instance.EnemyFoods[MainAttack]))
            {
                GameObject mapgrid = MapManager._instance.GetMapGridGo(mapid);
                if (mapgrid.transform.childCount >= 1)
                {
                    if (mapgrid.transform.GetChild(0).gameObject.tag == "PlayerFood")
                    {
                        bestPosNum.elseNum++;
                    }
                    else
                    {
                        bestPosNum.selfNum++;
                    }
                }
            }
            bestPosNum.Calnum = bestPosNum.elseNum + bestPosNum.selfNum;
            bestPosNum.pos = i;
            bestPosList.Add(bestPosNum);
        }


        //然后看自己是不是可以放技能，根据自己的类型选择在敌人多还是自己多的地方
        if (TeamManager._instance.EnemyFoods[MainAttack].Energy >= TeamManager._instance.EnemyFoods[MainAttack].skillInfo.energy)
        {
            if (TeamManager._instance.EnemyFoods[MainAttack].skillInfo.skilltype != SkillType.Health)
            {
                bestPosList.Sort(new ElseComparer());
                Debug.Log(bestPosList[0].pos + "_______Else");
                return bestPosList[0].pos;

            }
            else
            {
                bestPosList.Sort(new SelfComparer());
                Debug.Log(bestPosList[0].pos + "_______Self");
                return bestPosList[0].pos;
            }
        }
        else
        {
            bestPosList.Sort(new SumComparer());
            Debug.Log(bestPosList[0].pos + "_______Sum");
            return bestPosList[0].pos;
        }
    }


    public void PlayEffect()
    {
        if (MainAttack >= TeamManager._instance.EnemyFoods.Count)
        {
            MainAttack = 0;
        }
        else
        {
            Debug.Log("敌人" + MainAttack + TeamManager._instance.EnemyFoods[MainAttack].foodInfo.FoodName);
            if (TeamManager._instance.EnemyFoods[MainAttack].foodGo == null)
            {
                Debug.Log("敌人"+TeamManager._instance.PlayerFoods[MainAttack].foodInfo.FoodName + "为空");
                RoundIndex++;
                MainAttack++;
                PlayEffect();
            }
            else
            {
                string tag = TeamManager._instance.EnemyFoods[MainAttack].foodGo.tag;
                SkillManager._instance.UseSkill(TeamManager._instance.EnemyFoods[MainAttack], tag);               
            }           
        }
    }

    public void PlayDamage()
    {
        //造成伤害
        for (int i = 0; i < TeamManager._instance.PlayerFoods.Count; i++)
        {
            if (TeamManager._instance.PlayerFoods[i].foodGo != null)
            {
                foreach (int a in TeamManager._instance.EnemyFoods[MainAttack].AttackRangeMapGridID)
                {
                    int mapgridid = MapManager._instance.CalcuMapGridID(TeamManager._instance.PlayerFoods[i].foodPosX, TeamManager._instance.PlayerFoods[i].foodPosY);

                    if (a == mapgridid)
                    {
                        isDamagePlayer = true;
                        Debug.Log("在第" + RoundIndex + "回合" + "敌人   " + TeamManager._instance.EnemyFoods[MainAttack].foodInfo.FoodName + "   对你的   " + TeamManager._instance.PlayerFoods[i].foodInfo.FoodName + "   造成了" + TeamManager._instance.EnemyFoods[MainAttack].foodInfo.AttackForce + "点伤害");
                        TeamManager._instance.PlayerFoods[i].OnDamage(TeamManager._instance.EnemyFoods[MainAttack].foodInfo.AttackForce);
                        Combo++;
                        ComboHealth += TeamManager._instance.EnemyFoods[MainAttack].foodInfo.AttackForce;
                    }
                }
            }
        }

        if (isDamagePlayer)
        {
            TeamManager._instance.EnemyFoods[MainAttack].Energy++;
            TeamManager._instance.EnemyFoods[MainAttack].foodView.SetEnergyView(TeamManager._instance.EnemyFoods[MainAttack].Energy);
        }
        isDamagePlayer = false;

        AddEnergy();
    }


    public void AddHealth()
    {
        foreach (Food food in TeamManager._instance.EnemyFoods)
        {
            foreach (int mapgridid in TeamManager._instance.EnemyFoods[MainAttack].AttackRangeMapGridID)
            {
                int temp = MapManager._instance.CalcuMapGridID(food.foodPosX, food.foodPosY);

                if (temp == mapgridid)
                {
                    TeamManager._instance.CurrenEnemyHealth += TeamManager._instance.EnemyFoods[MainAttack].foodInfo.AttackForce;
                    HealthInfoView._instance.UpdateHealth();
                    food.foodView.ShowDamage(TeamManager._instance.EnemyFoods[MainAttack].foodInfo.AttackForce.ToString(), Color.green);
                }
            }
        }
        AddEnergy();
    }


    public void AddEnergy()
    {
        //增加能量
        foreach (Food food in TeamManager._instance.EnemyFoods)
        {
            foreach (int mapgridid in TeamManager._instance.EnemyFoods[MainAttack].AttackRangeMapGridID)
            {
                int temp = MapManager._instance.CalcuMapGridID(food.foodPosX, food.foodPosY);

                if (temp == mapgridid)
                {

                    Debug.Log(food.foodInfo.FoodName + "能量增加1点");
                    HelpFooder.Add(food);
                }
            }
        }

        if (HelpFooder != null)
        {
            FoodHelper();
        }
        else
        {
            if (TeamManager._instance.CurrenPlayerHealth <= 0)
            {
                TurnGame._instance.mState = OperatorState.PlayerQuit;
                TurnGame._instance.GameControl();
            }
            else
            {
                StartCoroutine("GoOnAttack");
            }
        }

    }

    private void FoodHelper()
    {
        if (HelpAttacker < HelpFooder.Count)
        {
            string tag = "EnemyHelp";
            HelpFooder[HelpAttacker].foodView.PlayerAttackEffect(HelpFooder[HelpAttacker].AttackRangeMapGridID, tag);
        }
        else
        {
            if (TeamManager._instance.CurrenPlayerHealth <= 0)
            {
                TurnGame._instance.mState = OperatorState.PlayerQuit;
                TurnGame._instance.GameControl();
            }
            else
            {
                StartCoroutine("GoOnAttack");
            }
        }
    }

    public void HelpDamage()
    {
        //造成伤害
        for (int i = 0; i < TeamManager._instance.PlayerFoods.Count; i++)
        {
            if (TeamManager._instance.PlayerFoods[i].foodGo != null)
            {
                foreach (int a in HelpFooder[HelpAttacker].AttackRangeMapGridID)
                {
                    int mapgridid = MapManager._instance.CalcuMapGridID(TeamManager._instance.PlayerFoods[i].foodPosX, TeamManager._instance.PlayerFoods[i].foodPosY);

                    if (a == mapgridid)
                    {
                        isDamagePlayer = true;
                        Debug.Log("  【帮助攻击】    " + "敌人   " + HelpFooder[HelpAttacker].foodInfo.FoodName + "   对你的   " + TeamManager._instance.PlayerFoods[i].foodInfo.FoodName + "   造成了" + HelpFooder[HelpAttacker].foodInfo.AttackForce + "点伤害");
                        TeamManager._instance.PlayerFoods[i].OnDamage(HelpFooder[HelpAttacker].foodInfo.AttackForce);
                        Combo++;
                        ComboHealth += HelpFooder[HelpAttacker].foodInfo.AttackForce;
                    }
                }
            }
        }

        if (isDamagePlayer)
        {
            HelpFooder[HelpAttacker].Energy++;
            HelpFooder[HelpAttacker].foodView.SetEnergyView(HelpFooder[HelpAttacker].Energy);
        }
        isDamagePlayer = false;

        HelpAttacker++;
        FoodHelper();
    }

    public void HelpHealth()
    {
        foreach (Food food in TeamManager._instance.EnemyFoods)
        {
            foreach (int mapgridid in HelpFooder[HelpAttacker].AttackRangeMapGridID)
            {
                int temp = MapManager._instance.CalcuMapGridID(food.foodPosX, food.foodPosY);

                if (temp == mapgridid)
                {
                    TeamManager._instance.CurrenEnemyHealth += HelpFooder[HelpAttacker].foodInfo.AttackForce;
                    HealthInfoView._instance.UpdateHealth();
                    food.foodView.ShowDamage(HelpFooder[HelpAttacker].foodInfo.AttackForce.ToString(), Color.green);
                }
            }
        }
        HelpAttacker++;
        FoodHelper();
    }

    IEnumerator GoOnAttack()
    {
        yield return new WaitForSeconds(1f);
        RoundIndex++;
        MainAttack++;
        if (MainAttack >= TeamManager._instance.EnemyFoods.Count)
        {
            MainAttack = 0;
        }
        SkillManager._instance.BuffClear();
        Combo = 0;
        ComboHealth = 0;
        TurnGame._instance.mState = OperatorState.PlayerRound;
        TurnGame._instance.GameControl();
    }
}


/// <summary>
/// 根据数量之和来判断
/// </summary>
public class SumComparer : IComparer<BestPosNum>
{
    public int Compare(BestPosNum x, BestPosNum y)
    {
        if (x.Calnum > y.Calnum)
            return -1;
        else if (x.Calnum == y.Calnum)
            return 0;
        else
            return 1;
    }
}

/// <summary>
/// 根据自己人来判断
/// </summary>
public class SelfComparer : IComparer<BestPosNum>
{
    public int Compare(BestPosNum x, BestPosNum y)
    {
        if (x.selfNum > y.selfNum)
            return -1;
        else if (x.selfNum == y.selfNum)
            return 0;
        else
            return 1;
    }
}

/// <summary>
/// 根据其他人来判断
/// </summary>
public class ElseComparer : IComparer<BestPosNum>
{
    public int Compare(BestPosNum x, BestPosNum y)
    {
        if (x.elseNum > y.elseNum)
            return -1;
        else if (x.elseNum == y.elseNum)
            return 0;
        else
            return 1;
    }
}